//
//  WritelnspectionVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/31.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Photos
import SwiftyJSON


class WriteInspectionVC: BaseVC {

  // 属性传值,必须
  var regionNumber: String!
  // 是否从功能里面来,然后刷新页面
  var isFromFunc: Bool = false
    var typeName: String!
    var parentVC: UIViewController?
    var assets: [String: [PHAsset]] = [:] {
        didSet {
            for cell in tableView.visibleCells {
                if cell is SelectImageViewCell {
                    let c = cell as? SelectImageViewCell
                    if c?.typeName == typeName {
                        c?.assets = assets[typeName] ?? []
                    }
                }
            }
            
        }
    }
  fileprivate var tableView: UITableView!
    fileprivate var assetIdentifier = ""
  
  fileprivate var formModel: InspectionFormModel?
    fileprivate var selectImageV: SelectImagePopV!
    fileprivate func takePhoto() {
        
        if assets.count >= 4 {
            SJHint.show("你已经选择了四张啦")
            return
        }
        
        if GlobalConfig.isAuthorizationVideo() {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            self.present(imagePicker, animated: true, completion: nil)
        }
        
    }
  fileprivate var models = [[String: String]]()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = GlobalConfig.BGWhiteColor
    
    create()
    pullData()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    GlobalConfig.baiduStatisticsPageViewStart("巡检表单")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    GlobalConfig.baiduStatisticsPageViewEnd("巡检表单")
  }
  
}

// MARK: - fileprivate

extension WriteInspectionVC {
  
    fileprivate func submitAction() {
        for (key, value) in assets {
            if value.count < 1 {
                assets.removeValue(forKey: key)
            }
        }
        
        
        for dic in models {
            // 必填项
            if "1" == dic["isNeed"] {
                if "Image" == dic["style"] {
                    if let i = self.assets[dic["key"] ?? ""] {
                        continue
                    }
                }
                if "DateRange" == dic["style"] {
                    guard let startTime = dic["startTime"], let endTime = dic["endTime"] else { return }
                        if startTime.isEmpty || endTime.isEmpty {
                        SJHint.show("有必填项未填写!")
                        let temp = dic["index"]!.sj.intValue
                        let indexPath = IndexPath.init(row: temp, section: 1)
                        self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                        return
                    }
                }

                if dic["value"]!.isEmpty {
                    SJHint.show("有必填项未填写!")
                    let temp = dic["index"]!.sj.intValue
                    let indexPath = IndexPath.init(row: temp, section: 1)
                    self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                    return
                }
            }

            if "1" == dic["isNumber"] {
                let number = dic["value"]!
                if !number.sj.isNumberAndPoint {
                    SJHint.show("只能填写数字!")
                    let temp = dic["index"]!.sj.intValue
                    let indexPath = IndexPath.init(row: temp, section: 1)
                    self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                    return
                }
            }
        }
    
        var _models:[Any] = []
        func submitInspectionForm(_ images: [String: Any] = [:], isOver: Bool = false) {
            for dic in models {
                var temp:[String: Any] = dic
                if dic["style"] == "Image" {
                    temp["value"] = images[dic["key"] ?? ""]
                }
                temp["tag"] = nil
                temp["isNeed"] = nil
                temp["index"] = nil
                temp["isNumber"] = nil
                _models.append(temp)
            }
            
            
            if isOver {
                let data = try? JSONSerialization.data(withJSONObject: _models, options: .prettyPrinted)
                let jsonString = String.init(data: data!, encoding: .utf8)
                
                SJApp.showHUD()
                let _ = WorkorderRequest.shared.submitInspectionForm(areaId: formModel!.id, resultData: jsonString ?? "") {
                    if self.isFromFunc {
                        let vcs = self.navigationController!.viewControllers
                        for vc in vcs {
                            if vc.isKind(of: PatrolInspectionVC.self) {
                                self.navigationController!.popToViewController(vc, animated: true)
                                break;
                            }
                        }
                        GlobalConfig.notificationCenter.post(name: Notification.Name.inspection.updateFunctionTodayInspection, object: nil)
                    }
                    else {
                        self.parentVC?.navigationController?.popToRootViewController(animated: true)
                        GlobalConfig.notificationCenter.post(name: Notification.Name.updateHome.updateHomeInspectionData, object: nil)
                    }
                    SJHint.show("提交成功")
                }
            }
            
        }
        
        
        if (assets.count > 0) {
            SJApp.endEdit()
            SJApp.showHUD()
            
            runInBackground {
                var i:Int = 0
                var images: [String:Any] = [:]
                for (key, assets) in self.assets {
                    
                    var tempDatas: [Data] = []
                    let uploadImages = PhotoHelper.fetchOriginalPhotos(with: assets)
                    
                    for uploadImage in uploadImages {
                        tempDatas.append(uploadImage.uploadData)
                    }
                    
                    let _ = FileRequest.shared.newUploadImages(datas: tempDatas, progressClosure: { (progress) in
                    }) { (ids) in
                        i += 1
                        images[key] = ids
                        if i == self.assets.keys.count {
                            submitInspectionForm(images, isOver: true)
                        }
                    }
                }
                
                
            }
        } else {
            submitInspectionForm([:], isOver: true)
        }
        
        
        
    
  }
  
  fileprivate func pullData() {
    
    SJApp.showHUD()
    let _ = WorkorderRequest.shared.getInspectionForm(areaNumber: regionNumber) { (inspectionFormmodel) in
      if "" == inspectionFormmodel.id {
        SJHint.show("没有该巡检项目")
        return
      }
      
      self.formModel = inspectionFormmodel
      
      for (index, item) in inspectionFormmodel.formItems.enumerated() {
        var dic = Dictionary<String, String>()
        dic["value"] = ""
        
        if item.required {
          dic["name"] = item.name
          dic["isNeed"] = "1"
        } else {
          dic["name"] = item.name + "(选填)"
          dic["isNeed"] = "0"
        }
        
        dic["tag"] = ""
        dic["index"] = "\(index)"
        
        dic["isNumber"] = ""
        if "Figure" == item.type {
          dic["isNumber"] = "1"
        }
        dic["startTime"] = ""
        dic["endTime"] = ""
        dic["style"] = ""
        
        self.models.append(dic)
      }
      
      self.tableView.reloadData()
      
    }
    
  }
  
  fileprivate func create() {
    
    addBackItem()
    
    tableView = UITableView()
    tableView.backgroundColor = UIColor.clear
    tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.register(OrderTitleCell.self, forCellReuseIdentifier: OrderTitleCell.identifier)
    tableView.register(InspectionRadioCell.self, forCellReuseIdentifier: InspectionRadioCell.identifier)
    tableView.register(InspectionMultiSelectCell.self, forCellReuseIdentifier: InspectionMultiSelectCell.identifier)
    tableView.register(InspectionInputCell.self, forCellReuseIdentifier: InspectionInputCell.identifier)
    tableView.register(ButtonCell.self, forCellReuseIdentifier: ButtonCell.identifier)
    tableView.register(InspectionInputCustomCell.self, forCellReuseIdentifier: InspectionInputCustomCell.identifier)
    tableView.register(DateRangeFormCell.self, forCellReuseIdentifier: DateRangeFormCell.identifier)
    tableView.register(SelectImageViewCell.self, forCellReuseIdentifier: SelectImageViewCell.identifier)
    view.addSubview(tableView)
    
    selectImageV = SelectImagePopV(frame: UIScreen.main.bounds)
    
    selectImageV.takePhotoClosure = { [unowned self] in self.takePhoto() }
    
    selectImageV.selectClosure = { [unowned self] in
        let photoPicker = PhotoPicker(selectedCount: 0, maxCount: 4, delegate: self)
        photoPicker.selectedAsset = self.assets[self.typeName] ?? []
        self.navigationController?.pushViewController(photoPicker, animated: true)
    }
  }
  
}

// MARK: - UITableViewDataSource

extension WriteInspectionVC : UITableViewDataSource {
  
  func numberOfSections(in tableView: UITableView) -> Int { return 3 }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    guard let _ = formModel else { return 0 }
    
    if 0 == section { return 1 }
    if 1 == section { return formModel?.formItems.count ?? 0 }
    return 1
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    // 上方表单信息
    if 0 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: OrderTitleCell.identifier) as! OrderTitleCell
      
      cell.inspectionModel = formModel
      return cell
    }
    // 表单信息
    else if 1 == indexPath.section {
    
      let cellType = formModel?.formItems[indexPath.row].type ?? ""
      
      self.models[indexPath.row]["index"] = "\(indexPath.row)"
      // 单选框
      if "Radio" == cellType {
        let cell = tableView.dequeueReusableCell(withIdentifier: InspectionRadioCell.identifier) as! InspectionRadioCell
        
        if formModel?.formItems[indexPath.row].required ?? true {
          cell.name = formModel?.formItems[indexPath.row].name ?? ""
        } else {
          cell.name = formModel!.formItems[indexPath.row].name + "(选填)"
        }
    
        cell.titles = formModel?.formItems[indexPath.row].options ?? []
        
        
        if let tag = self.models[indexPath.row].safeObject(forKey: "tag") {
          
          if (tag as! String).isEmpty {
            cell.selectIndex = -1
          } else {
            cell.selectIndex = (tag as! String).sj.intValue
          }
          
        } else {
          cell.selectIndex = -1
        }
        
        cell.getSelect = { (tag, name, title) in
          
          self.models[indexPath.row]["name"] = name
          self.models[indexPath.row]["value"] = title
          self.models[indexPath.row]["tag"] = tag
          
        }
        self.models[indexPath.row]["style"] = "Radio"
        return cell
        
      }
      // 复选框
      else if "Checkbox" == cellType {
      
        let cell = tableView.dequeueReusableCell(withIdentifier: InspectionMultiSelectCell.identifier) as! InspectionMultiSelectCell
        
        if formModel?.formItems[indexPath.row].required ?? true {
          cell.name = formModel?.formItems[indexPath.row].name ?? ""
        } else {
          cell.name = formModel!.formItems[indexPath.row].name + "(选填)"
        }
        
        
        cell.titles = formModel?.formItems[indexPath.row].options ?? []
        
        if let tags = self.models[indexPath.row].safeObject(forKey: "tag") {
          
          // MARK: - 这里不知道为啥会为空字符串
          if !(tags as! String).isEmpty {
            
            let temps = (tags as! String).components(separatedBy: ",")
            
            let stringTags = temps.map({
              return $0.sj.intValue
            })
            
            cell.selectIndexs = stringTags
            
          } else { cell.selectIndexs = [] }
          
        } else { cell.selectIndexs = [] }
        
        cell.getSelect = { (tags, name, titles) in
          
          self.models[indexPath.row]["name"] = name
          self.models[indexPath.row]["value"] = titles
          self.models[indexPath.row]["tag"] = tags
          
        }
        self.models[indexPath.row]["style"] = "Checkbox"
        return cell
        
      }
      // 其他
      else {
        
        if "Select" == cellType {
          
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCustomCell.identifier) as! InspectionInputCustomCell
          cell.options = formModel?.formItems[indexPath.row].options ?? []
          cell.type = .pullMenu
          
          if formModel?.formItems[indexPath.row].required ?? true {
            cell.name = formModel?.formItems[indexPath.row].name ?? ""
          } else {
            cell.name = formModel!.formItems[indexPath.row].name + "(选填)"
          }
          
          cell.options = formModel?.formItems[indexPath.row].options ?? []
          
          cell.getSelect = { (name, text) in
            
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
            
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            
            if (text as! String).isEmpty {
              cell.content = ""
            } else {
              cell.content = (text as! String)
            }
            
          }
          else {
              cell.content = ""
          }
          self.models[indexPath.row]["style"] = "Select"
          return cell
          
        }
        else if "Textarea" == cellType || "Input" == cellType {
          
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCell.identifier) as! InspectionInputCell
          cell.type = .text
          
          if formModel?.formItems[indexPath.row].required ?? true {
            cell.name = formModel?.formItems[indexPath.row].name ?? ""
          } else {
            cell.name = formModel!.formItems[indexPath.row].name + "(选填)"
          }
          
          cell.getSelect = { (name, text) in
            
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
            
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            
            if (text as! String).isEmpty {
              cell.content = ""
            } else {
              cell.content = (text as! String)
            }
          }
          else {
            cell.content = ""
          }
          self.models[indexPath.row]["style"] = "Textarea"
          return cell
          
        }
        else if "Figure" == cellType {
          
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCell.identifier) as! InspectionInputCell
          cell.type = .number
          
          if formModel?.formItems[indexPath.row].required ?? true {
            cell.name = formModel?.formItems[indexPath.row].name ?? ""
          } else {
            cell.name = formModel!.formItems[indexPath.row].name + "(选填)"
          }
          
          cell.getSelect = { (name, text) in
            
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
            
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            
            if (text as! String).isEmpty {
              cell.content = ""
            } else {
              cell.content = (text as! String)
            }
          }
          else {
            cell.content = ""
          }
          self.models[indexPath.row]["style"] = "Figure"
          return cell
          
        }
        else if "Date" == cellType {
          
          let cell = tableView.dequeueReusableCell(withIdentifier: InspectionInputCustomCell.identifier) as! InspectionInputCustomCell
          cell.type = .date
          cell.options = []
          
          if formModel?.formItems[indexPath.row].required ?? true {
            cell.name = formModel?.formItems[indexPath.row].name ?? ""
          } else {
            cell.name = formModel!.formItems[indexPath.row].name + "(选填)"
          }
          
          cell.getSelect = { (name, text) in
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = text
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "value") {
            if (text as! String).isEmpty {
              cell.content = ""
            } else {
              cell.content = (text as! String)
            }
          }
          else {
            cell.content = ""
          }
          self.models[indexPath.row]["style"] = "Date"
          return cell
          
        }
        else if "DateRange" == cellType {
          let cell = tableView.dequeueReusableCell(withIdentifier: DateRangeFormCell.identifier) as! DateRangeFormCell
          cell.model = formModel?.formItems[indexPath.row]
          
          if let text = self.models[indexPath.row].safeObject(forKey: "startTime") {
            cell.start = text as! String
          }
          
          if let text = self.models[indexPath.row].safeObject(forKey: "endTime") {
            cell.end = text as! String
          }
          
          cell.getTime = { (start, end , name) in
            self.models[indexPath.row]["name"] = name
            self.models[indexPath.row]["value"] = start + "," + end
            self.models[indexPath.row]["startTime"] = start
            self.models[indexPath.row]["endTime"] = end
          }
          
          self.models[indexPath.row]["style"] = "DateRange"
          return cell
        } else if "Image" == cellType {
            let cell = tableView.dequeueReusableCell(withIdentifier: SelectImageViewCell.identifier, for: indexPath) as! SelectImageViewCell
            
            let model: FormItem = (formModel?.formItems[indexPath.row])!
            cell.titleName = model.name
            
            
            let key = "\(model.type)-\(indexPath.row)"
            cell.typeName = key
            cell.assets = self.assets[key] ?? []
            cell.addPhotoClosure = { [unowned self] in
                SJApp.endEdit()
                self.typeName = key
                self.selectImageV.show(in: self.navigationController!.view!)
            }
            
            cell.deleteClosure = { [unowned self] index in
                SJApp.endEdit()
                self.assets[key]?.remove(at: index)
            }
            
            cell.cellDidClickAction = { [unowned self] index in
                SJApp.endEdit()
                
                let viewer = PhotoViewer(with: self.assets[key]!, enterIndex: index)
                self.navigationController?.pushViewController(viewer, animated: true)
            }
            
            self.models[indexPath.row]["style"] = "Image"
            self.models[indexPath.row]["key"] = key
            
            cell.mainView.snp.updateConstraints { (make) in
                make.top.equalTo(5)
            }
            
            return cell
        }
        
        return UITableViewCell()
      }
    }
    // 提交按钮
    else {
      
      let cell = tableView.dequeueReusableCell(withIdentifier: ButtonCell.identifier) as! ButtonCell
      cell.title = "提交"
      cell.buttonClick = { self.submitAction() }
      return cell
      
    }
  }
}

// MARK: - UITableViewDelegate

extension WriteInspectionVC : UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
    if 0 == indexPath.section {
      return OrderTitleCell.heightWithTitle(title: formModel?.areaName ?? "") - 30
    }
    else if 1 == indexPath.section {
      
      let cellType = formModel?.formItems[indexPath.row].type ?? ""
      
      if "Radio" == cellType {
        return InspectionRadioCell.height(with: formModel?.formItems[indexPath.row].options ?? [])
      } else if "Checkbox" == cellType {
        return InspectionMultiSelectCell.height(with: formModel?.formItems[indexPath.row].options ?? [])
      } else if "Textarea" == cellType{ return 200 }
      else if "DateRange" == cellType { return 180 }
      else if "Image" == cellType{ return (UIScreen.width - 80) / 4 + 15 + 30 + 40 + 5 }
      else { return 150 }
      
    }
    else { return ButtonCell.height }
    
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
    if 1 == section {
      let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
      view.backgroundColor = UIColor.clear
      return view
    }
    
    return nil
    
  }
  
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    
    if 1 == section { return 5 }
    return 0
    
  }
  
  
}
extension WriteInspectionVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)) , nil)
        
        runOnMainThread({
            picker.dismiss(animated: true) {
                
            }
        })
    }
    func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
        
        if didFinishSavingWithError != nil {
            return
        }
        let options = PHFetchOptions()
        options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: false)]
        let assetsFetchResults = PHAsset.fetchAssets(with: options)
        
        guard let asset = assetsFetchResults.firstObject else {
            SJHint.show("获取照片失败, 请重新拍摄")
            return
        }
        var assetsArr = self.assets[typeName] ?? []
        assetsArr.append(asset)
        
        self.assets[typeName] = assetsArr
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        runOnMainThread({
            picker.dismiss(animated: true) { }
        })
    }
    
}
extension WriteInspectionVC: PhotoPickerDelegate {
    func photoPickerDidFinishSelected(_ assets: [PHAsset]) {
        self.assets[typeName] = assets
    }
}
